package usr;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import page.PageState;

public class UsrModify extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession sess = req.getSession();
		Usr usr = (Usr)sess.getAttribute("usr");
		if( usr == null )
		{
			req.setAttribute("error_cause", PageState.LOGIN_NOT_EXIST);
			req.getRequestDispatcher("login.jsp").forward(req, resp);
			return;
		}
		String email = usr.getEmail();
		String password = usr.getPassword();
	
		usr.setEmail(req.getParameter("user[email]"));
		usr.setPassword(req.getParameter("user[password]"));
		
		if ( usr.getPassword().length() < 6 ) {
			req.setAttribute("error_cause", PageState.PASSWORD_TOO_SHORT);

		} else if ( !usr.getPassword().equals(
				req.getParameter("user[password_confirmation]")) ) {
			req.setAttribute("error_cause", PageState.PASSWORD_NOT_CONSIST);
		
		} else {
			int i = usr.getEmail().indexOf('@');
			int j = usr.getEmail().indexOf('.', i);
			
			if ( i < 0 || j < 0 || j - i < 2 ) {
				req.setAttribute("error_cause", PageState.NOT_AN_EMAIL);
				
			} else {
				i = usr.modify();
				if ( i != PageState.SUCCESSFUL ) {
					req.setAttribute("error_cause", i);
					
				} else { // in fact, not only error can use error cause
					req.setAttribute("error_cause", i);
					req.getRequestDispatcher("user.jsp").forward(req, resp);
					return;
				}
			}
		}
		// recover to the old value
		usr.setEmail(email);
		usr.setPassword(password);
		req.getRequestDispatcher("user.jsp").forward(req, resp);
	}
}
